﻿using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class GameClient : UniBrickClient
{
    private readonly Dictionary<string, Transform> _networkPlayers;
    public readonly Loom Loom;
    public readonly Transform MinifigModel;

    public string Username;

    public GameClient(Transform minfigModel)
    {
        _networkPlayers = new Dictionary<string, Transform>();
        Loom = Loom.Current;
        MinifigModel = minfigModel;
    }

    public override void CreatePlayer(string playerName)
    {
        Loom.QueueOnMainThread(() =>
        {
            var newPlayer = Object.Instantiate(MinifigModel);
            _networkPlayers.Add(playerName, newPlayer);
        });
    }

    public override void RemovePlayer(string playerName)
    {
        Loom.QueueOnMainThread(() =>
        {
            Object.Destroy(_networkPlayers[playerName]);
            _networkPlayers.Remove(playerName);
        });
    }

    public override void UpdatePlayer(string playerName, Vector3 position, Quaternion rotation)
    {
        if (_networkPlayers.ContainsKey(playerName))
            _networkPlayers[playerName].transform.position = position;
    }

    public override void UpdatePlayers(List<string> playerList)
    {
        foreach (var playerName in playerList.Where(playerName => !_networkPlayers.ContainsKey(playerName)).Where(playerName => playerName != Username))
        {
            CreatePlayer(playerName);
            Debug.Log(playerName + "_a");
        }

        foreach (var playerName in _networkPlayers.Keys.Where(playerName => !playerList.Contains(playerName)).Where(playerName => playerName != Username))
        {
            RemovePlayer(playerName);
            Debug.Log(playerName + "_r");
        }
    }
}